﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dotnet.Utils.Utility
{
    public class ExceptionUtil
    {
        /// <summary>
        /// 获取报错信息
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static string GetExMessage(string typeName, Exception ex)
        {

            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
            var frame = trace.GetFrame(0);
            var frame2 = trace.GetFrame(trace.FrameCount - 1);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append($"[{typeName}报错]：报错信息：");
            stringBuilder.AppendLine().Append("时间" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture));
            stringBuilder.AppendLine().AppendFormat("ex：{0}", ex.ToString());
            stringBuilder.AppendLine().AppendFormat("Message：{0}", ex.Message);
            stringBuilder.AppendLine().AppendFormat("StackTrace：{0}", ex.StackTrace);
            stringBuilder.AppendLine().AppendFormat("Source：{0}", ex.Source);
            stringBuilder.AppendLine().AppendFormat("Type：{0}", ex.GetType());
            stringBuilder.AppendLine().AppendFormat("Model：{0}", frame?.GetMethod()?.ReflectedType?.FullName);
            stringBuilder.AppendLine().AppendFormat("Line：{0}", frame?.GetFileLineNumber());
            stringBuilder.AppendLine().AppendFormat("Column：{0}", frame?.GetFileColumnNumber());
            stringBuilder.AppendLine().AppendFormat("Model2：{0}", frame2?.GetMethod()?.ReflectedType?.FullName);
            stringBuilder.AppendLine().AppendFormat("Line2：{0}", frame2?.GetFileLineNumber());
            stringBuilder.AppendLine().AppendFormat("Column2：{0}", frame2?.GetFileColumnNumber());
            return stringBuilder.ToString();
        }
    }
}
